$(document).ready(function(){
	var locationInput = $('#caLocation');
	var loader = $('#caLocationLoader');
	var dropdown = $('#caLocationSearchResults');
	var container = $('#caContainer');
	var locationContainer = $('#caLocationContainer');
	var extendedContainer = $('#caExtendedContainer');
	var token = $('#caLocationToken');
	var tokenName = $('#caLocationTokenName');
	var tokenType = $('#caLocationTokenType');
	var mask = $('#caMask');
	var maskLoader = $('#caMaskLoader');
	var tag = $('#caTag');
	var locationType = null;
	var locationId = null;
	var locationName = null;
	var parentContainer = $('#caLocationSearchResultsContainer');
	var dropdownIsShown = true;
	var searchTimeout = null;
	var searchCache = new Cache();
	var resultCount = 0;
	var selectedDropdownItem = null;
	var selectedCountry = 'nl';
	var spamProtect = false;
	var spamProtectTimer = null;
	var settings = {
		minChars: 2,
		searchDelay: 400,
		url: 'ajaj/searchLocation',
		dropdownSelectedClass: 'hover',
		maxResultCount: 5
	};
	
	// Initialize date and time pickers.
	var min_date = new Date();
	min_date.setDate(min_date.getDate() - 7);
	
	// Date picker.
	$('#caDate').datepicker({
		minDate: min_date,
		dateFormat: 'dd-mm-yy',
		showAnim: false,
		showOtherMonths: true,
		selectOtherMonths: true,
		onSelect: function(dateText, inst){
			$('#caTime').focus();
		}
	});
	
	// Date picker.
	$('#caEndDate').datepicker({
		minDate: min_date,
		dateFormat: 'dd-mm-yy',
		showAnim: false,
		showOtherMonths: true,
		selectOtherMonths: true,
		onSelect: function(dateText, inst){
			$('#caEndTime').focus();
		}
	});
	
	// Timepickers.
	$('.timepicker').timepicker({
		showLeadingZero: true,
		showAnim: false,
		defaultTime: 'now',
		showPeriodLabels: false,
		hourText: 'Uur',
		minuteText: 'Minuten',
		onClose: function(){
			$('#caWithWho').focus();
		}
	});
	
	// Fix focus.
	$('.timepicker').keydown(function(e){
		if(e.keyCode === keys.tab){
			return false;
		}
	});
	
	// Hide the dropdown and token by default.
	hideDropdown();
	token.hide();
	extendedContainer.hide();
	
	// Eindtijd toevoegen.
	$('#caWhenEndContainer').hide();
	$('#caWhenEndToggler').click(function(){
		$('#caWhenEndContainer').show();
		$(this).hide();
		$('#caEndDate').focus();
	});
	
	token.click(function(){
		revokeFormExtend();
	});
	
	locationInput.focus(function(){
		if(resultCount > 0){
			showDropdown();
		}
	
		if(!dropdownIsShown){
			showTooltip(locationInput);
		}
	}).blur(function(){
		hideTooltips();
		
		setTimeout(function(){
			hideDropdown();
		}, 200);
	}).keydown(function(e){
		switch(e.keyCode){
			case keys.left:
			case keys.right:
			case keys.up:
			case keys.down:
				var dropdownItem = null;
				
				if(e.keyCode === keys.down || e.keyCode === keys.right){
					dropdownItem = $(selectedDropdownItem).next();
				} else {
					dropdownItem = $(selectedDropdownItem).prev();
				}
				
				if(dropdownItem.length){
					selectDropdownItem(dropdownItem);
				}
				
				return false;
				break;
			case keys.enter:
			case keys.numpadEnter:
				if(selectedDropdownItem){
					pickItem($(selectedDropdownItem));
					return false;
				}
				break;
			default:
	            if(String.fromCharCode(e.which)) {
	                setTimeout(function(){
	                	doSearch();
	                }, 5);
	            }
            break;
		}
	});
	
	$('#caLocationSearchResults li').live('click', function(e){
		pickItem($(this));
	});
	
	$('#caPublish').click(function(){
		createActivity();
	});
	
	function createActivity(){
		if(spamProtect === false){
			maskLoader.show();
			mask.show();
			mask.animate({
				'opacity': 0.7
			}, 1000);
			
			// Reset values if they are equal to the placeholder ones!
			if($('#caDate').val() === $('#caDate').attr('placeholder')){
				$('#caDate').val('');
			}
			if($('#caTime').val() === $('#caTime').attr('placeholder')){
				$('#caTime').val('');
			}
			if($('#caEndDate').val() === $('#caEndDate').attr('placeholder')){
				$('#caEndDate').val('');
			}
			if($('#caEndTime').val() === $('#caEndTime').attr('placeholder')){
				$('#caEndTime').val('');
			}
			if($('#caWithWho').val() === $('#caWithWho').attr('placeholder')){
				$('#caWithWho').val('');
			}
			if($('#tokenInputcaTag').val() === $('#caTag').attr('placeholder')){
				$('#tokenInputcaTag').val('');
			}
			
			// Not working yet!! WTF
			if($('#caTag').val() === $('#caTag').attr('placeholder')){
				$('#caTag').val('');
			}
			
			// Do the actual call.
			$.ajax({
				url: 'ajaj/createActivity',
				dataType: 'json',
				type: 'POST',
				data: {
					date: $('#caDate').val(),
					time: $('#caTime').val(),
					endDate: $('#caEndDate').val(),
					endTime: $('#caEndTime').val(),
					destId: locationId,
					destType: locationType,
					withWho: $('#caWithWho').val(),
					tagText: $('#tokenInputcaTag').val(),
					tagId: $('#caTag').val()
				},
				timeout: 3000,
				success: function(response){
					if(response.error === 'ok'){
						showNot('Uw nieuwe activiteit is geplaatst');
						setSpamProtection();
						
						extendedContainer.css({
							'position': 'absolute'
						});
						
						extendedContainer.animate({
							top: '+=20px'
						}, 200, function(){
							extendedContainer.animate({
								opacity: '0'
							}, 200, function(){
							
								// Update the stream (since we now created another one)
								updateStream(function(){
								var newElement = $('#latestItem');
								
								// Mark the first one since that one is new!
								newElement.css({
									'overflow': 'hidden',
									'height': '0px'
								});
								
								newElement.animate({
									height: 50
								}, 300);
								});
								
								resetForm();
							});
						});
					} else {
						if(respone.error === 'spam'){
							showNot('U moet even wachten met het plaatsen van een nieuwe activteit');
							setSpamProtection();
						}
						
						alert(response.error);
						maskLoader.hide();
						mask.hide();
					}
				}
			});
		} else {
			showNot('U moet even wachten met het plaatsen van een nieuwe activteit');
		}
	}
	
	function setSpamProtection(){
		clearTimeout(spamProtectTimer);
		spamProtect = true;
		spamProtectTimer = setTimeout(function(){
			spamProtect = false;
		}, 10000);
	}
	
	function setDefaultFlag(){
	}
	
	function resetForm(){
		resultCount = 0;
		extendedContainer.css({
			'position': 'relative',
			top: '0px',
			opacity: '1'
		});
		
		mask.hide();
		maskLoader.hide();
		
		locationType = 0;
		locationId = 0;
		locationInput.val('');
		locationContainer.show();
		setDefaultFlag();
		dropdown.empty();
		$('#caDate').val('');
		$('#caTime').val('');
		$('#caWhenEndToggler').show();
		$('#caWhenEndContainer').hide();
		tag.tokenInput('clear');
		$('#caWithWho').tokenInput('clear');
		extendedContainer.hide();
		hideTooltips();
		// locationInput.focus();
	}
	
	function pickItem(item){
		if(item.attr('id') === 'addLocation'){
			hideDropdown();
			
			var id = '#addLocationPopup';
			var maskHeight = $(document).height();
			var maskWidth = $(window).width();
	
			$('#mask').css({
				'width': maskWidth,
				'height': maskHeight,
				'opacity': 0.3
			}).show();
			
			$(id).css('top',  $(window).height() / 2-$(id).height() / 2);
			$(id).css('left', $(window).width() / 2-$(id).width() / 2);
			$(id).show();
		} else {
			if(item.hasClass('friend')){
				locationType = 2;
			} else if(item.hasClass('city')){
				locationType = 3;
			} else if(item.hasClass('company')){
				locationType = 1;
			}
			
			locationId = $(item).attr('id');
			locationName = $(item).find('.title').html();
			extendForm();
		}
	}
	
	function extendForm(){
		hideDropdown();
		
		// Set token values.
		tokenName.html(locationName);
		
		if(locationType === 1){
			tokenType.html('Locatie');
		} else if(locationType === 2){
			tokenType.html('Facebook vriend');
		} else if(locationType === 3){
			tokenType.html('Plaats');
		}
		
		locationContainer.hide();
		token.show();
		extendedContainer.show();
		
		// If the user has already filled in a date before 
		// (meaning the user is repicking their location) don't focus.
		if($('#caDate').val() === '' || $('#caDate').val() === $('#caDate').attr('placeholder')){
			$('#caDate').focus();
		}
	}
	
	function revokeFormExtend(){
		token.hide();
		extendedContainer.hide();
		locationContainer.show();
		locationInput.focus();
	}
	
	function showLoader(){
		loader.show();
	}
	
	function hideLoader(){
		loader.hide();
	}
	
	function showDropdown(){
		hideTooltips();
		parentContainer.show();
		dropdownIsShown = true;
	}
	
	function hideDropdown(){
		parentContainer.hide();
		dropdownIsShown = false;
	}
	
	function doSearch(){
		var keyword = locationInput.val().toLowerCase();
		
		if(keyword && keyword.length){
			if(keyword.length >= settings.minChars){
                showLoader();
				clearTimeout(searchTimeout);	
				
				searchTimeout = setTimeout(function(){
					runSearch(keyword);
				}, settings.searchDelay);
			}
		}
	}
	
	function runSearch(keyword){
		var cacheResults = searchCache.get(keyword);
		
		if(cacheResults){
			populateDropdown(cacheResults);
		} else {
			$.ajax({
				url: settings.url,
				dataType: 'json',
				type: 'POST',
				data: {
					'keyword': keyword,
					'country': selectedCountry
				},
				success: function(results){
					searchCache.add(keyword, results);
					populateDropdown(results);
				}
			});
		}
	}
	
	function selectDropdownItem(item){
		if(item){
			if(selectedDropdownItem){
				deselectDropdownItem($(selectedDropdownItem));
			}
			
			item.addClass(settings.dropdownSelectedClass);
			selectedDropdownItem = item.get(0);
		}
	}
	
	function deselectDropdownItem(item){
		item.removeClass(settings.dropdownSelectedClass);
		selectedDropdownItem = null;
	}
	
	function populateDropdown(results){
		resultCount = 0;
		dropdown.empty();
		var totalCount = 0;
		
		if(results.cities){
			totalCount = totalCount = results.cities.length;
		}
		
		if(results.friends){
			totalCount = totalCount = results.friends.length;
		}
		
		if(results.companies){
			totalCount = totalCount = results.companies.length;
		}
		
		// Add "add location".
    	var li = '<li id="addLocation">Klik hier om een nieuwe locatie toe te voegen als de locatie niet wordt gevonden.</li>';
    	li = $(li).appendTo(dropdown);
		selectDropdownItem(li);
		
		dropdown.mouseover(function(event){
			selectDropdownItem($(event.target).closest("li"))
		});
		
		if(results.cities){
			$.each(results.cities, function(index, value){
				// Create the html of the li.
				var li = '<li class="city" id="' + value.id + '">';
				
				// The profile pictures. not supporting city pictures yet!
				// li += '<div class="profilePicture"><img src="https://graph.facebook.com/' + value.friendUserId + '/picture" alt="' + ucwords(value.name) + '" /></div>';
				
				// The table with the information of the user.
				li += '<table class="content">';
					li += '<tr>';
						li += '<td class="title">' + ucwords(value.name) + '</td>';
					li += '</tr>';
					li += '<tr>';
						li += '<td class="type">Plaats</td>';
					li += '</tr>';
					li += '<tr>';
						li += '<td class="subTitle"></td>';
					li += '</tr>';
				li += '</table>';
				li += '<div class="clear"></div></li>';
				li = $(li);
				
				if(resultCount === 0){
					selectDropdownItem(li);
				}
				
				resultCount++;
				
				if(resultCount === totalCount){
					li.addClass('last');	
				}
				
				li.appendTo(dropdown);
			});
		}
		
		if(results.friends){
			$.each(results.friends, function(index, value){
				// Create the html of the li.
				var li = '<li class="friend" id="' + value.friendUserId + '">';
				
				// The profile pictures.
				li += '<div class="profilePicture"><img src="https://graph.facebook.com/' + value.friendUserId + '/picture" alt="' + ucwords(value.name) + '" /></div>';
				
				// The table with the information of the user.
				li += '<table class="content">';
					li += '<tr>';
						li += '<td class="title">' + ucwords(value.name) + '</td>';
					li += '</tr>';
					li += '<tr>';
						li += '<td class="type">Facebook vriend</td>';
					li += '</tr>';
					
					if(value.onHikle){
						li += '<tr>';
							li += '<td class="subTitle">Maakt gebruik van Hikle.</td>';
						li += '</tr>';
					}
				li += '</table>';
				li += '<div class="clear"></div></li>';
				li = $(li);
				
				if(resultCount === 0){
					selectDropdownItem(li);
				}
				
				resultCount++;
				
				if(resultCount === totalCount){
					li.addClass('last');	
				}
				
				li.appendTo(dropdown);
			});
		}
		
		if(results.companies){
			$.each(results.companies, function(index, value){
			
				// Create the html of the li.
				var li = '<li class="company" id="' + value.id + '">';
				
				// The profile pictures. not supporting company pictures yet!
				// li += '<div class="profilePicture"><img src="https://graph.facebook.com/' + value.friendUserId + '/picture" alt="' + ucwords(value.name) + '" /></div>';
				
				// The table with the information of the user.
				li += '<table class="content">';
					li += '<tr>';
						li += '<td class="title">' + ucwords(value.name) + '</td>';
					li += '</tr>';
					li += '<tr>';
						li += '<td class="type">' + ucwords(value.branch) + '</td>';
					li += '</tr>';
					li += '<tr>';
						li += '<td class="subTitle">' + ucwords(value.city) + '</td>';
					li += '</tr>';
				li += '</table>';
				li += '<div class="clear"></div></li>';
				li = $(li);
				
				if(resultCount === 0){
					selectDropdownItem(li);
				}
				
				resultCount++;
				
				if(resultCount === totalCount){
					li.addClass('last');	
				}
				
				li.appendTo(dropdown);
			});
		}
		
		if(resultCount > 0){
			showDropdown();
		} else {
			hideDropdown();
		}
		
		hideLoader();
	}
	
	tag.tokenInput('ajaj/searchTags', {
		minChars: 2,
		searchDelay: 400,
		tokenLimit: 1,
		tokenValue: 'id',
		preventDuplicates: true,
		resultsFormatter: function(item){
			return '<li>' + ucwords(item['title']) + '</li>';
		},
        tokenFormatter: function(item){
            return '<li>' + ucwords(item['title']) + '</li>';
        }
	});
});